var tinymce_dle_plugin_loaded = false;
var playlist = '';

tinymce.PluginManager.add('dlebutton', function(editor, url) {
    editor.on('init', function() {

    	if (!tinymce_dle_plugin_loaded) {
    		tinymce_dle_plugin_loaded = true;
	        var cssURL = url + '/dlebutton.css';
	        if(document.createStyleSheet){
	            document.createStyleSheet(cssURL);
	        } else {
	            cssLink = editor.dom.create('link', {
	                        rel: 'stylesheet',
	                        href: cssURL
	                      });
	            document.getElementsByTagName('head')[0].
	                      appendChild(cssLink);
	        }
	    }
    });

    var scriptLoader = new tinymce.dom.ScriptLoader(),
        tp,
        typo = function () {
            if (tp) {
                editor.setContent(tp.execute(editor.getContent()));
                editor.undoManager.add();
            }
        };

    scriptLoader.add(url + '/typograf.min.js');

    scriptLoader.loadQueue(function () {
    	tp = new Typograf({
    		locale: ['ru', 'en-US'],
    		htmlEntity: {type: 'name', onlyInvisible: true}
		});

		tp.disableRule('common/space/afterPunctuation');
		tp.disableRule('common/space/delBeforePunctuation');

    });

    editor.addButton('dletypo', {
        title: 'Typographical Word Processing',
        icon: 'dleicon icon-typo',
        onclick: typo
    });

    editor.addMenuItem('dletypo', {
        context: 'format',
        title: 'Typographical Word Processing',
        icon: 'dleicon icon-typo',
        onclick: typo
    });

	editor.addButton('dleemo', {
		title : 'Add emoticons',
		icon : 'emoticons',
		onclick : function() {
			editor.windowManager.open({
			    title: "Add emoticons",
			    url: editor.settings.dle_root + 'engine/editor/jscripts/tiny_mce/plugins/emoticons/emotions.php',
			    width: 390,
			    height: 350
			});
		}
    });

	editor.addButton('dleupload', {
		title : 'Uploading files',
		icon : 'dleicon icon-up',
		onclick : function() {
			editor.focus();
			media_upload( editor.settings.dle_upload_area, editor.settings.dle_upload_user, editor.settings.dle_upload_news, '2');
		}
    });

	editor.addMenuItem('dleleech', {
		text: 'Insert protected link',
		icon : 'dleicon icon-leech',
		context: 'insert',
		onclick: function() {

            editor.windowManager.open({
                title: 'Insert protected link',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                }],
                onsubmit: function(e) {
                   editor.insertContent('[leech=' +e.data.href +']' + e.data.href +'[/leech]');
                }
            });

		}
	});
	editor.addButton('dleleech', {
		title : 'Insert protected link',
		icon : 'dleicon icon-leech',
		onclick : function() {
            editor.windowManager.open({
                title: 'Insert protected link',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                },
                {type: 'textbox', 
				    name: 'descr', 
				    label: 'Description', 
				    value: editor.selection.getContent()
				}],
                onsubmit: function(e) {
                   editor.insertContent('[leech=' +e.data.href+']' + e.data.descr +'[/leech]');
                }
            });
		}
    });

	editor.addMenuItem('dlequote', {
		text: 'Insert quote',
		icon : 'dleicon icon-quote',
		context: 'insert',
		onclick: function() {
			if( editor.selection.getContent() ) {
				editor.execCommand('mceReplaceContent',false,'<div class="quote">' + editor.selection.getContent() + '</div>');
			} else {
				editor.windowManager.open({
					title: 'Insert quote',
					body: [{
						type: 'textbox',
						name: 'qttext',
						style: 'width:500px;height:100px;',
						multiline: true,
						value: ''
					}],
					onsubmit: function(e) {
						
						var it = e.data.qttext.replace(/\n/g, '<br>');
						it = it.replace(/\r/g, '');
						editor.insertContent('<div class="quote">' +it +'</div>');
					}
				});
			}
		}
	});
	editor.addButton('dlequote', {
		title: 'Insert quote',
		icon : 'dleicon icon-quote',
			
		onclick: function() {
			
			if( editor.selection.getContent() ) {
				editor.execCommand('mceReplaceContent',false,'<div class="quote">' + editor.selection.getContent() + '</div>');
			} else {
				editor.windowManager.open({
					title: 'Insert quote',
					body: [{
						type: 'textbox',
						name: 'qttext',
						style: 'width:500px;height:100px;',
						multiline: true,
						value: ''
					}],
					onsubmit: function(e) {
						
						var it = e.data.qttext.replace(/\n/g, '<br>');
						it = it.replace(/\r/g, '');
						editor.insertContent('<div class="quote">' +it +'</div>');
					}
				});
			}

		}
	});
	editor.addMenuItem('dlehide', {
		text: 'Insert hidden text',
		icon : 'dleicon icon-hide',
		context: 'insert',
		onclick: function() {
			editor.execCommand('mceReplaceContent',false,'[hide]' + editor.selection.getContent() + '[/hide]');
		}
	});
	editor.addButton('dlehide', {
		title: 'Insert hidden text',
		icon : 'dleicon icon-hide',
			
		onclick: function() {
			editor.execCommand('mceReplaceContent',false,'[hide]' + editor.selection.getContent() + '[/hide]');
		}
	});
	editor.addMenuItem('dlecode', {
		text: 'Insert source code',
		icon : 'dleicon icon-code',
		context: 'insert',
		onclick: function() {
			editor.execCommand('mceReplaceContent',false,'[code]' + editor.selection.getContent() + '[/code]');
		}
	});
	editor.addButton('dlecode', {
		title : 'Insert source code',
		icon : 'dleicon icon-code',
		onclick : function() {
			editor.execCommand('mceReplaceContent',false,'[code]' + editor.selection.getContent() + '[/code]');
		}
    });
	editor.addMenuItem('dlemp', {
		text: 'Insert video (BB Codes)',
		icon : 'dleicon icon-video',
		context: 'insert',
		onclick: function() {
			editor.windowManager.open({
                title: 'Insert video (BB Codes)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                }],
                onsubmit: function(e) {
                   editor.insertContent('[video=' +e.data.href +']');
                }
            });
		}
	});
	editor.addButton('dlemp', {
		title : 'Insert video (BB Codes)',
		icon : 'dleicon icon-video',
		onclick : function() {
			var win = editor.windowManager.open({
                title: 'Insert video (BB Codes)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                },
				{type: 'textbox', 
				    name: 'descr', 
				    label: 'Description', 
				    value: ''
				},
				{type: 'textbox', 
				    name: 'poster', 
				    label: 'Link to poster', 
				    value: ''
				}
                ],
                buttons: [{
                    text: 'Insert',
					classes: 'widget btn primary first abs-layout-item',
					onclick: function(e) {
							win.submit();
						}
					}, {
                    text: 'Add to Playlist',
					classes: 'widget btn primary first abs-layout-item',
					onclick: function(e) {

								var videourl = win.find('#href').value();
								var videoposter = win.find('#poster').value();
								var videodescr = win.find('#descr').value();
								
								var videolink = videourl;

								if (videoposter != "" || videodescr != "" ) { 
									videolink += '|' + videoposter;
								}
								
								if (videodescr != "" ) { 
									videolink += '|' + videodescr;
								}
								
								if (videolink != "") {
									playlist +=  videolink + ',';
								}
								
								win.find('#href').value('');
								win.find('#descr').value('');
								win.find('#poster').value('');

							}
					}, {
					text: 'Close',
					onclick: 'close',
					}],
                onsubmit: function(e) {

					var videolink = win.find('#href').value();
					var poster = win.find('#poster').value();
					var descr = win.find('#descr').value();

					if (poster != "" || descr != "" ) { 
						videolink += '|' + poster;
					}
					
					if (descr != "" ) { 
						videolink += '|' + descr;
					}
					
					if(videolink != "" && videolink != "http://") {
						playlist += videolink;
					}else if(playlist != "") {
						playlist = playlist.substring(0, playlist.length - 1)
					}

					if(playlist != "") {
                   		editor.insertContent('[video=' + playlist +']');
                   	}

					playlist = '';
                }
            });
		}
    });
	editor.addMenuItem('dlaudio', {
		text: 'Insert audio (BB Codes)',
		icon : 'dleicon icon-audio',
		context: 'insert',
		onclick: function() {
			editor.windowManager.open({
                title: 'Insert audio (BB Codes)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                }],
                onsubmit: function(e) {
                   editor.insertContent('[audio=' +e.data.href +']');
                }
            });
		}
	});
	editor.addButton('dlaudio', {
		title : 'Insert audio (BB Codes)',
		icon : 'dleicon icon-audio',
		onclick : function() {
			var win = editor.windowManager.open({
                title: 'Insert audio (BB Codes)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                },
				{type: 'textbox', 
				    name: 'descr', 
				    label: 'Description', 
				    value: ''
				}
                ],
                buttons: [{
                    text: 'Insert',
					classes: 'widget btn primary first abs-layout-item',
					onclick: function(e) {
							win.submit();
						}
					}, {
                    text: 'Add to Playlist',
					classes: 'widget btn primary first abs-layout-item',
					onclick: function(e) {

								var videourl = win.find('#href').value();
								var videodescr = win.find('#descr').value();
								
								var videolink = videourl;
								
								if (videodescr != "" ) { 
									videolink += '|' + videodescr;
								}
								
								if (videolink != "") {
									playlist +=  videolink + ',';
								}
								
								win.find('#href').value('');
								win.find('#descr').value('');

							}
					}, {
					text: 'Close',
					onclick: 'close',
					}],
                onsubmit: function(e) {

					var videolink = win.find('#href').value();
					var descr = win.find('#descr').value();
					
					if (descr != "" ) { 
						videolink += '|' + descr;
					}
					
					if(videolink != "") {
						playlist += videolink;
					}else if(playlist != "") {
						playlist = playlist.substring(0, playlist.length - 1);
					}

					if(playlist != "") {
                   		editor.insertContent('[audio=' + playlist +']');
                   	}

					playlist = '';
                }
            });
		}
    });
	editor.addMenuItem('dletube', {
		text: 'Play video from youtube (Youtube)',
		icon : 'dleicon icon-yt',
		context: 'insert',
		onclick: function() {
			editor.windowManager.open({
                title: 'Play video from youtube (Youtube)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                }],
                onsubmit: function(e) {
                   editor.insertContent('[media=' +e.data.href +']');
                }
            });
		}
	});	
	editor.addButton('dletube', {
		title : 'Play video from youtube (Youtube)',
		icon : 'dleicon icon-yt',
		onclick : function() {
			editor.windowManager.open({
                title: 'Play video from youtube (Youtube)',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Url',
                    size: 40,
                    value: ''
                }],
                onsubmit: function(e) {
                   editor.insertContent('[media=' +e.data.href +']');
                }
            });
		}
    });
	editor.addMenuItem('dlespoiler', {
		text: 'Insert spoiler',
		icon : 'dleicon icon-spoiler',
		context: 'insert',
		onclick: function() {
			editor.execCommand('mceReplaceContent',false,'[spoiler]' + editor.selection.getContent() + '[/spoiler]');
		}
	});	
	editor.addButton('dlespoiler', {
		title : 'Insert spoiler',
		icon : 'dleicon icon-spoiler',
		onclick : function() {
			editor.execCommand('mceReplaceContent',false,'[spoiler]' + editor.selection.getContent() + '[/spoiler]');
		}
    });		
	editor.addMenuItem('dlebreak', {
		text: 'Insert page breaks',
		icon : 'dleicon icon-br',
		context: 'tools',
		onclick: function() {
			editor.execCommand('mceInsertContent',false,'{PAGEBREAK}');
		}
	});
	editor.addButton('dlebreak', {
		title : 'Insert page breaks',
		icon : 'dleicon icon-br',
		onclick : function() {
			editor.execCommand('mceInsertContent',false,'{PAGEBREAK}');
		}
    });	
	editor.addMenuItem('dlepage', {
		text: 'Insert link to the page',
		icon : 'dleicon icon-pl',
		context: 'tools',
		onclick: function() {
			editor.windowManager.open({
                title: 'Insert link to the page',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Page Number',
                    size: 10,
                    value: '1'
                }, {
                    type: 'textbox',
                    name: 'text',
                    label: 'Text to display',
                    size: 40,
                    value: editor.selection.getContent({ format: 'text' })
                }],
                onsubmit: function(e) {
                   editor.insertContent('[page=' +e.data.href +']' + e.data.text +'[/page]');
                }
            });

		}
	});
	editor.addButton('dlepage', {
		title : 'Insert link to the page',
		icon : 'dleicon icon-pl',
		onclick : function() {
			editor.windowManager.open({
                title: 'Insert link to the page',
                body: [{
                    type: 'textbox',
                    name: 'href',
                    label: 'Page Number',
                    size: 10,
                    value: '1'
                }, {
                    type: 'textbox',
                    name: 'text',
                    label: 'Text to display',
                    size: 40,
                    value: editor.selection.getContent({ format: 'text' })
                }],
                onsubmit: function(e) {
                   editor.insertContent('[page=' +e.data.href +']' + e.data.text +'[/page]');
                }
            });
		}
    });

	editor.addButton('dleimage', {
		title : 'Insert image',
		icon : 'image',
		onclick : function() {
			editor.windowManager.open({
                title: 'Insert image',
                body: [{
                    type: 'textbox',
                    name: 'href',
					size: 50,
                    label: 'Url'
                }, {
                    type: 'textbox',
                    name: 'text',
					size: 50,
                    label: 'Image description'
                }, {
                    type: 'listbox',
                    name: 'align',
                    label: 'Alignment',
					values : [
                        { text: 'None', value: '' },
                        { text: 'Left', value: 'left' },
                        { text: 'Right', value: 'right' },
						{ text: 'Center', value: 'center' }
                    ]
                }],
                onsubmit: function(e) {
					var imageurl = e.data.href;
					var imagealt = e.data.text;
					var imagealign = e.data.align;
					
					var imgoption = "";
			
					if (imagealt != "") { 
			
						imgoption = "|"+imagealt;
			
					}
			
					if (imagealign != "" && imagealign != "center") { 
			
						imgoption = imagealign+imgoption;
			
					}
			
					if (imgoption != "" ) {
			
						imgoption = "="+imgoption;
			
					}
			
					if (imagealign == "center") {
						editor.insertContent('<p style="text-align: center;">[img'+imgoption+']'+imageurl+'[/img]</p>');
					}
					else {
						editor.insertContent("[img"+imgoption+"]"+imageurl+"[/img]", "", false);
					}
                }
            });
		}
    });

});